package cn.lrwjz.geotest.bluetooth;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.lang.reflect.Method;
import java.util.ArrayList;

import cn.lrwjz.geotest.adapter.DeviceBluetoothAdapter;

/*
 * 蓝牙初始化类
 */
public class BlueToothInit implements IBlueToothInit {
    private Activity mActivity;
    private Context mContext;
    private BluetoothAdapter mBtAdapter;
    private DeviceBluetoothAdapter mAdapter;
    private static final int REQUEST_ENABLE_BT = 1;
    public static final int PERMISSIONS_REQUEST_CODE = 100;

    public BlueToothInit(Context context, BluetoothAdapter btAdapter, DeviceBluetoothAdapter adapter) {
        mAdapter = adapter;
        mActivity = (Activity) context;
        mContext = context;
        
        // 优先使用 BluetoothManager 获取适配器
        if (btAdapter == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            if (bluetoothManager != null) {
                btAdapter = bluetoothManager.getAdapter();
            }
        }
        mBtAdapter = btAdapter;
    }

    private boolean checkBluetoothPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_CONNECT) 
                    == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    //打开蓝牙
    @Override
    public void openBlueTooth() {
        if (mBtAdapter == null) {
            Toast.makeText(mContext, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mBtAdapter.isEnabled()) {
            if (!checkBluetoothPermission()) {
                requestPermission();
                return;
            }
            try {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                mActivity.startActivityForResult(intent, REQUEST_ENABLE_BT);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(mContext, "打开蓝牙失败，请手动开启", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //关闭蓝牙
    @Override
    public void closeBlueTooth() {
        if (!checkBluetoothPermission()) {
            return;
        }
        try {
            if (mBtAdapter != null && mBtAdapter.isEnabled()) {
                mBtAdapter.disable();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContext, "关闭蓝牙失败", Toast.LENGTH_SHORT).show();
        }
    }

    //判断蓝牙是否打开
    @Override
    public boolean isOpenBlueTooth() {
        if (mBtAdapter != null) {
            if (!checkBluetoothPermission()) {
                return false;
            }
            try {
                return mBtAdapter.isEnabled();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //搜索蓝牙
    @Override
    public void searchBlueTooth() {
        if (mBtAdapter == null) {
            Toast.makeText(mContext, "蓝牙不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.BLUETOOTH_SCAN) 
                    != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(mContext, "请先授予蓝牙扫描权限", Toast.LENGTH_SHORT).show();
                requestPermission();
                return;
            }
        }

        if (!mBtAdapter.isEnabled()) {
            Toast.makeText(mContext, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
            openBlueTooth();
            return;
        }

        try {
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
            mBtAdapter.startDiscovery();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContext, "搜索蓝牙设备失败", Toast.LENGTH_SHORT).show();
        }
    }

    //搜索蓝牙前请求权限
    @Override
    public boolean requestPermission() {
        mAdapter.clearData();
        return checkPermission();
    }

    private boolean checkPermission() {
        ArrayList<String> permissions = new ArrayList<>();

        // 基础权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        // 存储权限（按需添加）
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        // Android 12 (API 31)及以上版本的蓝牙权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions.add(Manifest.permission.BLUETOOTH_SCAN);
            permissions.add(Manifest.permission.BLUETOOTH_CONNECT);
            permissions.add(Manifest.permission.BLUETOOTH_ADVERTISE);
        } else {
            permissions.add(Manifest.permission.BLUETOOTH);
            permissions.add(Manifest.permission.BLUETOOTH_ADMIN);
        }

        ArrayList<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(mContext, permission) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(mActivity, 
                    permissionsToRequest.toArray(new String[0]), 
                    PERMISSIONS_REQUEST_CODE);
            return false;
        }

        return true;
    }

    //返回匹配状态
    @Override
    public boolean getBondState(BluetoothDevice device) {
        if (device == null) {
            return false;
        }

        if (!checkBluetoothPermission()) {
            Toast.makeText(mContext, "请先授予蓝牙连接权限", Toast.LENGTH_SHORT).show();
            return false;
        }

        try {
            int bondState = device.getBondState();
            if (BluetoothDevice.BOND_NONE == bondState) {
                Method createBond = BluetoothDevice.class.getMethod("createBond");
                return (Boolean) createBond.invoke(device);
            } else if (BluetoothDevice.BOND_BONDED == bondState) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContext, "配对失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    //停止搜索蓝牙
    @Override
    public void stopSearchBlueTooth() {
        if (!checkBluetoothPermission()) {
            return;
        }

        try {
            if (mBtAdapter != null && mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContext, "停止搜索失败", Toast.LENGTH_SHORT).show();
        }
    }
}
